package leetcode_链表;

import general_class.ListNode;

/**
 * 两两交换链表中的节点
 * 算法：迭代、递归
 *
 * @author yezh
 * @date 2024/1/11 10:24
 */
public class _24 {

    public ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) return head;
        ListNode next = head.next.next, newHead = head.next;
        newHead.next = head;
        head.next = swapPairs(next);
        return newHead;
    }

    public ListNode swapPairs_iterate(ListNode head) {
        ListNode dummy = new ListNode(), cur = dummy, next;
        dummy.next = head;
        while (head != null && head.next != null) {
            next = head.next.next;
            cur.next = head.next;
            head.next.next = head;
            head.next = next;
            head = next;
            cur = cur.next.next;
        }
        return dummy.next;
    }

}
